<?php
/**
Plugin Name: cBlogger Robot
Plugin URI: http://wordpress.org/#
Description: cBoggger Robot โปรแกรม Auto Post Blogger 
Author: Pattarawut Channgam
Version: 1.0.1
*/

	
function cbrobot_install() {

	global $wpdb;
	$cbrobot_table_queues = $wpdb->prefix . "cbrobot_queues";

	$cbrobot_db_version = "1.0";

	if($wpdb->get_var("SHOW TABLES LIKE '$cbrobot_table_queues'") != $cbrobot_table_queues) {
		
		$sql[] = "CREATE TABLE ".$cbrobot_table_queues." (
		`id` bigint(20) NOT NULL auto_increment,
		`blog_id` varchar(100) NOT NULL,
		`blog_email` varchar(100) NOT NULL,
		`blog_password` varchar(100) NOT NULL,
		`blog_url` varchar(100) NOT NULL,
		`asin` varchar(50) NOT NULL,
		`title` text NOT NULL,
		`content` longtext NOT NULL,
		`queue_time` varchar(50) NOT NULL,
		`queue_status` varchar(1) NOT NULL,
		PRIMARY KEY  (`id`),
		UNIQUE KEY `asin` (`asin`)
		)";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        //execute the query creating our table 
		dbDelta($sql);
		//save the table structure version number
		add_option("cbrobot_db_version", $cbrobot_db_version);
	}

	$installed_ver = get_option( "cbrobot_db_version" );
	if( $installed_ver != $cbrobot_db_version ) {
		//update database table here
		//update table version 
		update_option( "cbrobot_db_version", $cbrobot_db_version );
	}
	

}
register_activation_hook(__FILE__, 'cbrobot_install');

function cbrobot_uninstall() {
	global $wpdb;
	delete_option('cbrobot_options');
	wp_clear_scheduled_hook('cbrobot_job_event');
	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

	$cbrobot_table_queues = $wpdb->prefix . "cbrobot_queues";
	
	$sql = "DROP TABLE ".$cbrobot_table_queues.";";
	$wpdb->query($sql);
    dbDelta($sql);
	
    
}
register_deactivation_hook(__FILE__, 'cbrobot_uninstall');

add_action('cbrobot_job_event', 'do_cronjob');

function cbrobot_create_cronjob() {
	$options = unserialize(get_option("cbrobot_options"));	
	if ( !wp_next_scheduled( 'cbrobot_job_event' ) ) {
		wp_schedule_event(time(), $options['cbrobot_time'], 'cbrobot_job_event');
	}
}

function do_cronjob() {
	// do something every hour
	global $wpdb;
	$options = unserialize(get_option("cbrobot_options"));	
	$sql = "SELECT * 
			        FROM " . $wpdb->prefix."cbrobot_queues 
					WHERE queue_status <> 'Y'
					ORDER BY id ";
			
	$records = $wpdb->get_results($sql); 
	if ($records) {
		$i = 0;
		foreach ($records as $record) { 
			post_data($record->id);
			if($i==$options['cbrobot_number_post'] || $i==count($records)) { break; }
			$i++;
		}
	}
}

add_action('admin_menu', 'cbrobot_add_pages');

function cbrobot_add_pages() {

	add_menu_page('cbrobot', 'cBlogger Robot', 8, 'cbrobot-options', 'cbrobot_options');
	add_submenu_page('cbrobot-options', 'Options', 'Options', 8, 'cbrobot-options', 'cbrobot_options');
	add_submenu_page('cbrobot-options', 'Queues', 'Queues', 8, 'cbrobot-queues', 'cbrobot_queues');
	add_submenu_page('cbrobot-options', 'Template', 'Template', 8, 'cbrobot-template', 'cbrobot_template');
}

function cbrobot_options() {
	global $wpdb;
	$options = unserialize(get_option("cbrobot_options"));	
		?>
			<script type="text/javascript" src="<?php bloginfo( 'wpurl' ); ?>/wp-content/plugins/cbrobot/js/jquery.js"></script>
			<script type="text/javascript" src="<?php bloginfo( 'wpurl' ); ?>/wp-content/plugins/cbrobot/js/jquery.validate.js"></script>
			<script type="text/javascript" > 
				       $().ready(function() {
							$("#cbrobot_time").val('<?php echo $options[cbrobot_time]; ?>');
			           });
			</script>
			<?php

	if($_POST['cbrobot_amazon_save']) {
			$options['cbrobot_aa_affkey'] = $_POST['cbrobot_aa_affkey'];
			$options['cbrobot_aa_apikey'] = $_POST['cbrobot_aa_apikey'];
			$options['cbrobot_aa_secretkey'] = $_POST['cbrobot_aa_secretkey'];
			$options['cbrobot_username'] = $_POST['cbrobot_username'];
			$options['cbrobot_password'] = $_POST['cbrobot_password'];

			update_option("cbrobot_options", serialize($options));
			echo '<div class="updated"><p>'.__('Options have updated.', 'cbrobot').'</p></div>';	
	}

	if($_POST['cbrobot_cron_start']) {
			$options['cbrobot_number_post'] = $_POST['cbrobot_number_post'];
			$options['cbrobot_time'] = $_POST['cbrobot_time'];
			update_option("cbrobot_options", serialize($options));

			cbrobot_create_cronjob();
			//do_cronjob();
			echo '<div class="updated"><p>'.__('Cron Job have Started.', 'cbrobot').'</p></div>';	
	}

	if($_POST['cbrobot_cron_stop']) {
			wp_clear_scheduled_hook('cbrobot_job_event');
	}

	include_once("display-options.php");
}

function cbrobot_queues(){
	?>
	<script type="text/javascript" src="<?php bloginfo( 'wpurl' ); ?>/wp-content/plugins/cbrobot/js/jquery.js"></script>
	<script type="text/javascript" src="<?php bloginfo( 'wpurl' ); ?>/wp-content/plugins/cbrobot/js/jquery.validate.js"></script>
<?php
	global $wpdb;
	$options = unserialize(get_option("cbrobot_options"));

	if($_POST['cbrobot_create_queue_save']) {
			$error = array();
			$blog_id = $_POST['cbrobot_bg_id'];
			$email = $_POST['cbrobot_bg_email'];
			$password = $_POST['cbrobot_bg_password'];
			$url = $_POST['cbrobot_bg_url'];
			$asin = $_POST['cbrobot_aa_asin'];

			
			if(!$blog_id) {
				echo '<div class="error"><p>***กรุณากรอก Blog Id***</p></div>';			
				$error[] = "E_ID";
			} 
			if(!$email) {
				echo '<div class="error"><p>***กรุณากรอก Email***</p></div>';
				$error[] = "E_EMAIL";
			}
			if(!$password) {
				echo '<div class="error"><p>***กรุณากรอก Password***</p></div>';
				$error[] = "E_PASSWORD";
			}
			if(!$url) {
				echo '<div class="error"><p>***กรุณากรอก URL***</p></div>';
				$error[] = "E_URL";
			}
			if(!$asin) {
				echo '<div class="error"><p>***กรุณากรอก Asin***</p></div>';
				$error[] = "E_ASIN";
			}
			
			if(count($error) == 0) {
				require_once("lib/content.php");
				require_once("lib/xmlrpc.php");
				$param = array();
				/* Load XML Template Config */
                $config = simplexml_load_file(ABSPATH."/wp-content/plugins/cbrobot/template.xml");
				$title = base64_decode($config->title);
				$content = base64_decode($config->content);

				$client = new IXR_Client('http://www.channgamsim.com/xmlrpc.php');

				$params = array(0,$options['cbrobot_username'],$options['cbrobot_password'],
					$options['cbrobot_aa_affkey'],$options['cbrobot_aa_apikey'],$options['cbrobot_aa_secretkey'],$asin);
				
				if (!$client->query('demo.test', $params)) {
					echo '<div class="error">***'.$client->getErrorCode().' : '.$client->getErrorMessage().'***</div>';
				}else {
					$obj_content = new Content();

					$val = $client->message->params[0][Items][Item];
					$title = $obj_content->getXML($val,$title,$keyword);
					$content = $obj_content->getXML($val,$content,$keyword);

					$title = Content::spin_content($title);
					$content = Content::spin_content($content);

					$sql = "INSERT INTO ".$wpdb->prefix."cbrobot_queues (blog_id, blog_email, blog_password, blog_url, asin, title, content, queue_time)
			            VALUES ('".trim($blog_id)."','".trim($email)."','".trim($password)."','".trim($url)."','".trim($asin)."',
						        '".trim(base64_encode($title))."','".trim(base64_encode($content))."','".time()."');";
				
					if($result=$wpdb->query($sql)) {
						echo '<div class="updated"><p>'.__('Insert Queue.', 'cbrobot').'</p></div>';	
					}else {
						echo '<div class="error">***Not Insert Data'.$result.'***</div>';
					}
					
				}

			}else{
			?>
			<script type="text/javascript" > 
				       $().ready(function() {
							$("#cbrobot_bg_id").val('<?php echo $blog_id; ?>');
							$("#cbrobot_bg_email").val('<?php echo $email; ?>');
							$("#cbrobot_bg_password").val('<?php echo $password; ?>');
							$("#cbrobot_bg_url").val('<?php echo $url; ?>');
							$("#cbrobot_aa_asin").val('<?php echo $asin; ?>');
			           });
			</script>
			<?php

			}
	}

	if($_GET['postdata']) {
		$id = $_GET['postdata'];
		post_data($id);
	}
	if($_GET['delete']) {
		$id= $_GET['delete'];
		delete_data($id);
	}
	include_once("display-queues.php");
}

function cbrobot_template() {
	/* Load XML Template Config */
    $config = simplexml_load_file(ABSPATH."/wp-content/plugins/cbrobot/template.xml");

	if($_POST['cbrobot_template_save']) {
		$title = $_POST['cbrobot_tp_title'];
		$content = $_POST['cbrobot_tp_content'];
		$title = stripslashes($title);
        $content = stripslashes($content);
        $title = base64_encode($title);
        $content = base64_encode($content);
		$xml = file_get_contents(ABSPATH."/wp-content/plugins/cbrobot/template.xml");
        $xml = str_replace("<title>".$config->title."</title>","<title>".$title."</title>",$xml);
        $xml = str_replace("<content>".$config->content."</content>","<content>".$content."</content>",$xml);
        if(@file_put_contents(ABSPATH."/wp-content/plugins/cbrobot/template.xml",$xml)) echo '<div class="updated">*** Tempate Update ***</div>';
	}

	if($_POST['cbrobot_default']) {
		$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
                   <config>
                        <title>e3RpdGxlfQ==</title>
                        <content>PGRpdiBzdHlsZT0iY2xlYXI6IGJvdGg7IHRleHQtYWxpZ246IGNlbnRlcjsiPg0KPGEgaHJlZj0ie3VybH0iIHRpdGxlPSJTZWV7dGl0bGV9IERldGFpbHMiPiANCjxpbWcgc3JjPSJ7bGFyZ2VpbWFnZX0iIGFsdD0ie3RpdGxlfSIgd2lkdGg9IjMwMHB4IiAvPjwvYT4gDQo8L2Rpdj4gDQo8ZGl2PjxzdHJvbmc+Q3VzdG9tZXIgUmF0aW5nPC9zdHJvbmc+IDogPGRpdj57cmF0aW5nfTwvZGl2PiANCjxzdHJvbmc+TGlzdCBQcmljZTwvc3Ryb25nPiA6IDxzcGFuIHN0eWxlPSJ0ZXh0LWRlY29yYXRpb246bGluZS10aHJvdWdoOyI+e2xpc3RwcmljZX08L3NwYW4+IDxzdHJvbmc+UHJpY2U8L3N0cm9uZz4gOiA8c3BhbiBzdHlsZT0iY29sb3I6I2U4MDAwMDtmb250LXNpemU6MS4zZW07Zm9udC13ZWlnaHQ6Ym9sZDsiPntwcmljZX08L3NwYW4+IA0KPGEgaHJlZj0ie3VybH0iIHRpdGxlPSJ7dGl0bGV9Ij48aW1nIHNyYz0iaHR0cDovL3d3dy5jaGFubmdhbXNpbS5jb20vd3AtY29udGVudC91cGxvYWRzLzIwMTIvMDMvZnVsbHJldmlld3MuZ2lmIiBhbHQ9Int0aXRsZX0iIC8+PC9hPg0KPC9kaXY+IA0Ke2NvbnRlbnR9DQp7ZmVhdHVyZXN9DQo8ZGl2IHN0eWxlPSJjbGVhcjogYm90aDsgdGV4dC1hbGlnbjogY2VudGVyOyI+IA0KPGEgaHJlZj0ie3VybH0iIHRpdGxlPSJDaGVjayBmb3IgTG93ZXN0IFByaWNlcyB7dGl0bGV9IiByZWw9Im5vZm9sbG93Ij4gPGltZyBzcmM9Imh0dHA6Ly93d3cuY2hhbm5nYW1zaW0uY29tL3dwLWNvbnRlbnQvdXBsb2Fkcy8yMDEyLzAzL2FkZF90b19jYXJ0LmpwZyIgYWx0PSJ7dGl0bGV9IiAvPjwvYT4NCjwvZGl2PiANCntyZXZpZXdzfQ==</content>
                   </config>";

            if(@file_put_contents(ABSPATH."/wp-content/plugins/cbrobot/template.xml",$xml)) echo '<div class="updated">*** Default Template ***</div>';
	}
	/* Load XML Template Config */
    $config = simplexml_load_file(ABSPATH."/wp-content/plugins/cbrobot/template.xml");
	include_once("display-template.php");
}

function post_data($id) {
		set_time_limit(0);
			
		require_once("Zend/Loader.php");
		require_once("lib/blogger.php");		
		Zend_Loader::loadClass('Zend_Gdata');
		Zend_Loader::loadClass('Zend_Gdata_Query');
		Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
		global $wpdb;
		$options = unserialize(get_option("cbrobot_options"));	
		
		try {

				$obj_blogger = new Blogger();
                $param = array();

				$sql = "SELECT * 
				        FROM ".$wpdb->prefix."cbrobot_queues 
						WHERE id = '".$id."'";
             
				$row = $wpdb->get_row($sql);

				if($row) {
					$param['title']   = base64_decode($row->title);
					$param['content'] = base64_decode($row->content);
					$param['blog_id'] = $row->blog_id;
					$param['email']   = $row->blog_email;
					$param['password']= $row->blog_password;
					if($obj_blogger->post($param)) {
						echo '<div class="updated"><p>'.__('Post Asin : '.$row->asin.' Success.', 'cbrobot').'</p></div>';
						flush();
						$wpdb->query("UPDATE ".$wpdb->prefix."cbrobot_queues SET queue_status = 'Y' WHERE id = '".$id."'");
						flush();
					}
				}
							
			}catch (Exception $e) {			
				echo '<div class="error"><p>'.__('***'.$e->getMessage().'***', 'cbrobot').'</p></div>';
				flush();
            } 	
}

function delete_data($id) {
	global $wpdb;
	$sql = "DELETE FROM ".$wpdb->prefix."cbrobot_queues 
			WHERE id = '".$id."'";
             
	$wpdb->query($sql);
}


function zend_gdata_interfaces_init() {
	//Check that the PHP version is at least 5
	if(! preg_match('/5\./', phpversion())) {
		add_action('admin_notices', 'zend_gdata_version_error');
	} else {
		$path = dirname(__FILE__);
	    set_include_path(get_include_path() . PATH_SEPARATOR . $path);
		define('WP_ZEND_GDATA_INTERFACES', true);
	    require_once 'Zend/Loader.php';
	}
}

function zend_gdata_version_error() {    
    $version = phpversion();
    echo <<<END_OF_HTML
    <div class='error'>
    <p><strong>
    Zend Gdata Interfaces: Your PHP installation is currently running PHP $version. The Zend Gdata Interfaces plugin requires PHP 5.1.4 or higher.
    </strong></p>
    </div>
END_OF_HTML;
}

add_action('plugins_loaded', 'zend_gdata_interfaces_init', 0);

?>